package org.dreamwork.jasmine2.sample.converter;

/**
 * Created by IntelliJ IDEA.
 * User: seth.yang
 * Date: 11-8-9
 * Time: 下午1:06
 */
import org.dreamwork.util.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CollectionConverter implements IXMLConverter<ICollection>, IJSONConverter<ICollection> {
    public ICollection convert (Class<ICollection> type, Node node) {
        ICollection<Class1> c = new Collection<Class1> ();
        NodeList list = ((Element) node).getElementsByTagName ("item");
        try {
            for (int i = 0; i < list.getLength (); i ++) {
                Class1 v = NodeConverter.parseNode (Class1.class, list.item (i));
                c.add (i + "", v);
            }
        } catch (Exception ex) {
            throw new ClassCastException (ex.getMessage ());
        }
        return c;
    }

    @SuppressWarnings ("unchecked")
    public void convert (Class<ICollection> type, ICollection bean, Node parent) {
        if (bean == null) return;
        Document doc = parent.getOwnerDocument ();
        for (Object o : bean) {
            Class t = o.getClass ();
            Element e = doc.createElement ("item");
            parent.appendChild (e);
            NodeConverter.parseObject (t, o, e);
        }
    }

    public ICollection convert (Class<ICollection> type, String expression) {
        return null;
    }

    public String convert (Class<ICollection> type, ICollection bean) {
        Map<String, Object> map = new HashMap<String, Object> ();
        Map<String, Object> values = new HashMap<String, Object> ();
        List<String> keys = new ArrayList<String> ();
        map.put ("count", bean.count ());
        map.put ("keys", keys);
        map.put ("values", values);
        for (int i = 0; i < bean.count (); i ++) {
            String key = bean.getKey (i);
            Object value = bean.get (i);
            keys.add (key);
            values.put (key, value);
        }

        return new JSConverter ().cast (map);
    }
}
